const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs');
require('dotenv').config();

async function createAdmin() {
  const connection = await mysql.createConnection({
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || 'qwer4321',
    database: process.env.DB_NAME || 'bar_system'
  });

  try {
    // 检查是否已存在管理员
    const [existing] = await connection.execute(
      'SELECT * FROM users WHERE phone = ?',
      ['13800138000']
    );

    if (existing.length > 0) {
      console.log('管理员账号已存在，更新密码...');
      const hashedPassword = await bcrypt.hash('admin123', 10);
      await connection.execute(
        'UPDATE users SET password = ?, role = ? WHERE phone = ?',
        [hashedPassword, 'admin', '13800138000']
      );
      console.log('✓ 管理员密码已更新');
    } else {
      console.log('创建新管理员账号...');
      const hashedPassword = await bcrypt.hash('admin123', 10);
      await connection.execute(
        'INSERT INTO users (name, phone, password, role, balance) VALUES (?, ?, ?, ?, ?)',
        ['管理员', '13800138000', hashedPassword, 'admin', 0]
      );
      console.log('✓ 管理员账号创建成功');
    }

    console.log('\n默认管理员账号信息:');
    console.log('手机号: 13800138000');
    console.log('密码: admin123');
    
  } catch (error) {
    console.error('错误:', error);
  } finally {
    await connection.end();
  }
}

createAdmin();
